package com.jcsz.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jcsz.common.to.es.SkuEsModel;
import com.jcsz.common.utils.R;
import com.jcsz.gulimall.search.config.GuliESConfig;
import com.jcsz.gulimall.search.constant.EsConstant;
import com.jcsz.gulimall.search.feign.ProductFeignService;
import com.jcsz.gulimall.search.service.MallSearchService;
import com.jcsz.gulimall.search.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: MallSearchServiceImpl
 * @author: 一把Po吉他
 * @date: 2022/11/3 11:13
 * @version: 1.0
 **/
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {

        //准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        //准备封装检索结果
        SearchResult result = null;
        try {
            //执行检索请求
            SearchResponse response = client.search(searchRequest, GuliESConfig.COMMON_OPTIONS);
            //封装检索结果
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * @param param
     * @return org.elasticsearch.action.search.SearchRequest
     * @description 通过请求参数动态构建DSL语句
     * @author 一把Po吉他
     * @date 2022/11/4 10:21
     **/
    private SearchRequest buildSearchRequest(SearchParam param) {
        //动态构建出需要查询的语句
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键词检索
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        //分类
        if (param.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //库存
        if (param.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        //品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));

        }
        //价格skuPrice形式为：1_500或_500或500_
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            String skuPrice = param.getSkuPrice();
            String[] price = skuPrice.split("_");
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            if (price.length == 2) {
                rangeQueryBuilder.gte(price[0]).lte(price[1]);
            } else if (price.length == 1) {
                if (skuPrice.startsWith("_")) {
                    rangeQueryBuilder.lte(price[1]);
                } else if (skuPrice.endsWith("_")) {
                    rangeQueryBuilder.gte(price[0]);
                }
            }

            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //属性attrs=1_5寸:8寸&2_16G:8G
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attr : param.getAttrs()) {
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }

        }
        //排序sort=hotScore_asc/desc
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] sortString = param.getSort().split("_");
            searchSourceBuilder.sort(sortString[0], sortString[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC);
        }
        //高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        //页面
        if (param.getPageNum() != null) {
            Integer pageNum = param.getPageNum();
            searchSourceBuilder.from((pageNum - 1) * EsConstant.PRODUCT_PAGESIZE);
            searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        }
        searchSourceBuilder.query(boolQueryBuilder);
        //查看检索条件
        System.out.println(searchSourceBuilder.toString());
        //构建品牌聚合
        TermsAggregationBuilder brand_id_agg = AggregationBuilders.terms("brand_id_agg");
        brand_id_agg.size(10).field("brandId");
        brand_id_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").size(1).field("brandName"));
        brand_id_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").size(1).field("brandImg"));
        searchSourceBuilder.aggregation(brand_id_agg);
        //构建分类聚合
        TermsAggregationBuilder catelog_id_agg = AggregationBuilders.terms("catelog_id_agg");
        catelog_id_agg.size(10).field("catalogId");
        catelog_id_agg.subAggregation(AggregationBuilders.terms("catelog_name_agg").size(1).field("catalogName"));
        searchSourceBuilder.aggregation(catelog_id_agg);
        //构建属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg");
        attr_id_agg.field("attrs.attrId");

        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg");
        attr_name_agg.field("attrs.attrName").size(10);
        attr_id_agg.subAggregation(attr_name_agg);

        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg");
        attr_value_agg.field("attrs.attrValue").size(10);
        attr_id_agg.subAggregation(attr_value_agg);

        nested.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(nested);
        //查看检索&聚合
        System.out.println(searchSourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();

        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //高亮
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle_ = hit.getHighlightFields().get("skuTitle");
                    String skuTitleString = skuTitle_.getFragments()[0].toString();
                    skuEsModel.setSkuTitle(skuTitleString);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        //所有的查询到的sku信息
        result.setProducts(skuEsModels);
        //分页信息
        if (param.getPageNum() != null) {
            result.setPageNum(param.getPageNum());
            result.setTotal(hits.getTotalHits().value);
            result.setTotalPages(hits.getTotalHits().value / EsConstant.PRODUCT_PAGESIZE == 0 ? (int)
                    (hits.getTotalHits().value / EsConstant.PRODUCT_PAGESIZE) : (int)
                    (hits.getTotalHits().value / EsConstant.PRODUCT_PAGESIZE) + 1);
        }
        //品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_id_agg = response.getAggregations().get("brand_id_agg");
        for (Terms.Bucket bucket : brand_id_agg.getBuckets()) {

            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);

            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //分类信息catelog_id_agg
        List<SearchResult.CatelogVo> catelogs = new ArrayList<>();
        ParsedLongTerms catelog_id_agg = response.getAggregations().get("catelog_id_agg");
        for (Terms.Bucket bucket : catelog_id_agg.getBuckets()) {
            SearchResult.CatelogVo catelogVo = new SearchResult.CatelogVo();
            long catelogId = bucket.getKeyAsNumber().longValue();
            catelogVo.setCatalogId(catelogId);

            ParsedStringTerms catelog_name_agg = bucket.getAggregations().get("catelog_name_agg");
            String catelogName = catelog_name_agg.getBuckets().get(0).getKeyAsString();
            catelogVo.setCatalogName(catelogName);
            catelogs.add(catelogVo);
        }
        result.setCatelogs(catelogs);
        //属性信息
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);

            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");

            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                String attrValue = item.getKeyAsString();
                return attrValue;
            }).collect(Collectors.toList());
            attrVo.setAttrValues(attrValues);

            attrs.add(attrVo);

        }
        result.setAttrs(attrs);
        //构建面包屑导航
        //属性
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navVos = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.info(Long.parseLong(s[0]));
                //属性Ids
                result.getAttrIds().add(Long.parseLong(s[0]));

                if (r.getCode() == 200) {
                    AttrResponseVo attrResponseVo = r.get("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(attrResponseVo.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                // 取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String replace = replaceQueryString(param, attr, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(navVos);
        }
        //品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            R r = productFeignService.getBrandByIds(param.getBrandId());
            if (r.getCode() == 200) {
                List<BrandVo> brands = r.get("brands", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer stringBuffer = new StringBuffer();
                String replace = "";
                for (BrandVo brand : brands) {
                    String brandName = brand.getName();
                    stringBuffer.append(brandName + ";");
                    replace = replaceQueryString(param, brand.getBrandId().toString(), "brandId");
                }
                String value = stringBuffer.substring(0, stringBuffer.lastIndexOf(";"));
                navVo.setNavName("品牌:");
                navVo.setNavValue(value);
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                navs.add(navVo);
            }
        }
        //分类
        if (param.getCatalog3Id() != null) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            R r = productFeignService.getCatelogTnfoById(param.getCatalog3Id());
            if (r.getCode() == 200) {
                Catelog3Vo catelog3Vo = r.get("categoryInfo", new TypeReference<Catelog3Vo>() {
                });

                String replace = replaceQueryString(param, catelog3Vo.getCatId().toString(), "catalog3Id");
                navVo.setNavName("分类:");
                navVo.setNavValue(catelog3Vo.getName());
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                navs.add(navVo);
            }
        }
        //查看结果
        System.out.println(result);
        return result;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("%28", "(");
            encode = encode.replace("%29", ")");
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String queryString = param.get_queryString();
        String replace = "";
        if (queryString.startsWith(key)) {
            replace = param.get_queryString().replace(key + "=" + encode, "");
        } else {
            replace = param.get_queryString().replace("&" + key + "=" + encode, "");
        }


        return replace;
    }

}
